#include "portScan.h"
#include "setFlags.h"
#include "buildpacket.h"
#include "portInfo.h"
#include <mutex>
#include <thread>
#include <netinet/in.h>
#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
void receive(int port,char* ip,char* mode){
    struct sockaddr_in src_addr;
    socklen_t src_addr_len = sizeof(src_addr);

    char buffer[BUFFSIZE];
    struct ip *ip_hdr;
    struct tcphdr *tcp_hdr;

    int rawSocket1;
    // 创建原始套接字，接收 TCP 数据包
    rawSocket1 = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
    if (rawSocket1 == -1) {
        perror("socket");
    }

    // 设置筛选条件，例如只接收来自特定源地址的数据包
    struct in_addr target_ip;
    if (inet_aton(ip, &target_ip) == 0) {
        perror("inet_aton");
        close(rawSocket1);
        return;
    }
}

void sendPacket(int port,char* ip,char* mode){

    dataPacket* packet = buildDataPacket(port,ip);
    struct sockaddr_in destAddr;

    // 初始化目标地址
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons(port); // 目标端口号
    inet_pton(AF_INET, ip, &(destAddr.sin_addr)); // 目标IP地址
    struct sockaddr_in server_addr;

    if(mode == "s"){
        synPortScan(&packet->tcp);
    }else if(mode == "f"){
        finPortScan(&packet->tcp);
    }else if(mode == "a"){
        ackPortScan(&packet->tcp);
    }else if(mode == "n"){
        nullPortScan(&packet->tcp);
    }else if(mode == "syn_ack"){
        syn_ackPortScan(&packet->tcp);
    }else if(mode == "x"){
        xmasPortScan(&packet->tcp);
    }else{
        std::cout<<"模式非法"<<std::endl; 
        return;
    }
    // 初始化 socket
    int rawSocket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    if (rawSocket == -1) {
        perror("socket");
        exit(1);
    }

    int optval = 1;
    int set = setsockopt(rawSocket, IPPROTO_IP, IP_HDRINCL, &optval, sizeof(optval));
    if (set == -1) {
        perror("set");
        close(rawSocket);
        exit(1);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(12345);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    bind(rawSocket, (struct sockaddr *)&server_addr, sizeof(server_addr));            

    std::thread recv_thread(receive, port,ip,mode);

    int sent = sendto(rawSocket, perror, ntohs(packet->ip.tot_len), 0, (struct sockaddr *)&destAddr, sizeof(destAddr));
    if (sent == -1) {
        perror("sendto");
        close(rawSocket);
        exit(1);
    }
    // 检查是否发送了预期的字节数
    if (sent != ntohs(packet->ip.tot_len)) {
        printf("Warning: Not all bytes were sent. Sent: %d, Expected: %d\n", sent, ntohs(packet->ip.tot_len));
    }

    recv_thread.join();
}
